import time
import datetime
import requests
# from pypushdeer import PushDeer
from BarkNotificator import BarkNotificator
# import json
import os


class PostPusher:
    # 类属性
    create_time = ""
    # 构造方法，用于初始化对象的属性
    def __init__(self, key, file_path, last_post_id):
        # 实例属性
        self.key = key
        self.file_path = file_path
        self.last_post_id = last_post_id

    def read_last_post_id(self):
        if self.last_post_id != "":
            return

        try:
            # 以只读模式打开文件
            with open(self.file_path, "r", encoding="utf-8") as file:
                content = file.read()
            print(f"从文件 {self.file_path} 中读取到的内容是: {content}")
            self.last_post_id = content
        except FileNotFoundError:
            print(f"文件 {self.file_path} 未找到。")
        except Exception as e:
            print(f"读取文件时出现错误: {e}")

    def write_last_post_id(self):
        try:
            # 以写入模式打开文件，如果文件不存在则创建
            with open(self.file_path, "w", encoding="utf-8") as file:
                file.write(self.last_post_id)
            print(f"成功将 {self.last_post_id} 写入文件 {self.file_path}")
        except Exception as e:
            print(f"写入文件时出现错误: {e}")

    def push(self, content):
        # url = f"https://api2.pushdeer.com/message/push?pushkey={self.key}&text={content}"
        # url = f"https://api2.pushdeer.com/message/push?pushkey={self.key}&text=发布时间:{self.create_time}&desp={content}&type=markdown"
        # requests.get(url, timeout=10)

        # pushdeer = PushDeer(pushkey=self.key)
        # pushdeer.send_markdown(
        #     f"发布时间:{self.create_time}", desp=content
        # )

        bark = BarkNotificator(device_token=self.key)
        bark.send(title=f"发布时间:{self.create_time}", content=content)

        # url = "https://api.day.app/push"
        # payload = {
        #     "title": f"发布时间:{self.create_time}",
        #     "body": content,
        #     "device_key": self.key,
        # }
        # headers = {"Content-Type": "application/json; charset=utf-8"}
        # json_data = json.dumps(payload)
        # requests.post(url=url,data=json_data,headers=headers,timeout=10)

    def query_user_profile_page_contents(self):
        url = "https://www.binance.com/bapi/composite/v9/friendly/pgc/content/queryUserProfilePageContents?targetSquareUid=TCMnFqpA2sfc6SfADf6NXw&timeOffset=-1&isQueryLivingContent=true"

        payload = {}
        headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
            "bnc-level": "0",
            "bnc-location": "BINANCE",
            "bnc-time-zone": "Asia/Shanghai",
            "bnc-uuid": "36f643ec-51c4-4461-8b3c-e057aa78af7b",
            "clienttype": "web",
            "content-type": "application/json",
            "csrftoken": "d41d8cd98f00b204e9800998ecf8427e",
            "device-info": "eyJzY3JlZW5fcmVzb2x1dGlvbiI6IjIwNDgsMTE1MiIsImF2YWlsYWJsZV9zY3JlZW5fcmVzb2x1dGlvbiI6IjE5OTcsMTEyNyIsInN5c3RlbV92ZXJzaW9uIjoiTWFjIE9TIDEwLjE1LjciLCJicmFuZF9tb2RlbCI6InVua25vd24iLCJzeXN0ZW1fbGFuZyI6InpoLUNOIiwidGltZXpvbmUiOiJHTVQrMDg6MDAiLCJ0aW1lem9uZU9mZnNldCI6LTQ4MCwidXNlcl9hZ2VudCI6Ik1vemlsbGEvNS4wIChNYWNpbnRvc2g7IEludGVsIE1hYyBPUyBYIDEwXzE1XzcpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS8xMzMuMC4wLjAgU2FmYXJpLzUzNy4zNiIsImxpc3RfcGx1Z2luIjoiUERGIFZpZXdlcixDaHJvbWUgUERGIFZpZXdlcixDaHJvbWl1bSBQREYgVmlld2VyLE1pY3Jvc29mdCBFZGdlIFBERiBWaWV3ZXIsV2ViS2l0IGJ1aWx0LWluIFBERiIsImNhbnZhc19jb2RlIjoiODc1MmVhOTUiLCJ3ZWJnbF92ZW5kb3IiOiJHb29nbGUgSW5jLiAoQXBwbGUpIiwid2ViZ2xfcmVuZGVyZXIiOiJBTkdMRSAoQXBwbGUsIEFOR0xFIE1ldGFsIFJlbmRlcmVyOiBBcHBsZSBNNCwgVW5zcGVjaWZpZWQgVmVyc2lvbikiLCJhdWRpbyI6IjEyNC4wNDM0NjYwNzExNDcxMiIsInBsYXRmb3JtIjoiTWFjSW50ZWwiLCJ3ZWJfdGltZXpvbmUiOiJBc2lhL1NoYW5naGFpIiwiZGV2aWNlX25hbWUiOiJDaHJvbWUgVjEzMy4wLjAuMCAoTWFjIE9TKSIsImZpbmdlcnByaW50IjoiMjZiZWRiMGY2ZjYxYThkNDc2OGM4ZmQwMTk4Nzk4ODAiLCJkZXZpY2VfaWQiOiIiLCJyZWxhdGVkX2RldmljZV9pZHMiOiIifQ==",
            "dnt": "1",
            "fvideo-id": "33f68509f3f0af94b471ffc03ac67b244820ca84",
            "fvideo-token": "jXFeHyXOna2+iPpAwMRXOkfZf+Mlvw1cDE3J+waJs5WH68sU9RAt/eJYB/BBqVWMyHSCF35r2VE8r9ICnOKytd47eO6ZNfUYHlI2787IoULYfryi9qkkr24kGwJe9Na8UEuTILZAqGuUcv6x/3Ad7J9KivXm/sBzNJU9PfuD09pShcGNZ3hvWo2zojNEpFV1g=02",
            "if-none-match": 'W/"02a7c497b15e5d161c6fcae6f79de3880"',
            "lang": "zh-CN",
            "priority": "u=1, i",
            "referer": "https://www.binance.com/zh-CN/square/profile/square-creator-7be28d989",
            "sec-ch-ua": '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"macOS"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
            "x-passthrough-token": "",
            "x-trace-id": "79883b9b-e10c-40b6-af12-e86689a4af6b",
            "x-ui-request-trace": "79883b9b-e10c-40b6-af12-e86689a4af6b",
        }


        status_code = 0
        rsp_text = ""
        try:
            response = requests.get(url, headers=headers, data=payload, timeout=10)
            status_code = response.status_code
            rsp_text = response.text
        except requests.exceptions.ConnectionError as e:
            print(f"Error connecting to the server: {e}")
        except requests.exceptions.HTTPError as e:
            print(f"HTTP error occurred: {e}")
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
        except Exception as e:
            print(f"other err: {e}")

        # 检查响应状态码
        if status_code != 200:
            print(f"请求失败，状态码: {status_code}")
            # 打印响应内容
            print(rsp_text)
            # else:
            print(f"请求失败，状态码: {response.status_code}")

        try:
            # 将响应内容解析为 Python 对象
            json_data = response.json()
            # print("解析后的 Python 对象类型:", type(json_data))
            # print("解析后的数据:", json_data)
        except ValueError:
            print("响应内容不是有效的 JSON 格式。")

        idx = 2
        post_id = str(json_data["data"]["contents"][idx]["id"])
        shareLink = json_data["data"]["contents"][idx]["shareLink"]
        text = json_data["data"]["contents"][idx]["bodyTextOnly"]
        # image_list = json_data["data"]["contents"][idx]["imageList"]
        # 给定的毫秒级时间戳
        timestamp_ms = json_data["data"]["contents"][idx]["createTime"]
        # 将毫秒转换为秒
        timestamp_s = timestamp_ms / 1000

        # 把秒级时间戳转换为 datetime 对象
        dt = datetime.datetime.fromtimestamp(timestamp_s)

        # 格式化 datetime 对象为年月日时分秒的字符串
        self.create_time = dt.strftime("%Y-%m-%d %H:%M:%S")

        print("解析后的数据:", post_id)
        if post_id != self.last_post_id:
            self.last_post_id = post_id
            self.write_last_post_id()
            # content = f"[{link}]({link})\n\n{text}"
            content = f"{shareLink}\n\n{text}"
            # for item in image_list:
            #     content+=f"![]({item})"
            self.push(content)


if __name__ == "__main__":
    # PushDeer
    # key = "PDU33885Tx7RPpCiio0MyRF0ySjZz2GVdGWF9rkWf"
    # bark
    # key = "2KzwDuZCgNSSqjqf6pRcZU"
    key = "5e926333c83d7bb5c9e65e2550ed9684e7d1357daa0f8d7cf865b57439c0aed0"
    file_path = f"{os.getcwd()}/lastPostId.txt"
    last_post_id = ""
    post_pusher = PostPusher(key, file_path, last_post_id)

    while True:
        # 获取当前时间
        now = datetime.datetime.now()
        print(now.strftime("%Y-%m-%d %H:%M:%S"))

        post_pusher.read_last_post_id()
        post_pusher.query_user_profile_page_contents()

        time.sleep(5 * 60)
